/*login.js*/
const router = require('koa-router')();
const utils = require('../utils')
const download = require('../apis/download')
const login = require('../apis/login')
const logout = require('../apis/logout')
const session = require('../middleware/session')

const handler = api => {
	return async function (ctx) {
		let func = require('../' + api.fileName)
		let func_name = api.path.match(/([\w|-]+)$/)[0]
		if (func_name) {
			ctx.response.body = await func[func_name](ctx)
		} else {
			ctx.response.body = { success: false, errorCode: 404 }
		}
	}
}
module.exports = app => {
	router.post('/login', login)
	router.use(session)//.use(authorize());

	utils.readApiJson(apis => {
		apis.forEach(api => {
			router.get(api.path, handler(api))
			router.post(api.path, handler(api))
		})

		// router.delete('/api/file/directories', query.directories);
		// router.put('/api/file/directories', query.directories);
		// 对应方法
		router.get('/api/metas/file/:appName/:fileName', download.file)
		router.get('/logout', logout)

		// user login
		/* router.all('/login', ctx => {
			ctx.redirect('/sign-in');
			ctx.status = 301;
		}); */

		app.use(router.routes()).use(router.allowedMethods());
	})
}